package com.feng.chat.utils;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {
    public static String secretKey="dyf_hh^_^";
    public static long expiresIn=24*60*60*1000;

    /**
     * 创建token
     * @param id
     * @return
     */
    public static String createToken(String id){
        String token = Jwts.builder().setSubject(id)
                .setExpiration(new Date(System.currentTimeMillis() + expiresIn))
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Integer parserToken(String token){
        if (token.contains("Bearer")){
            String id = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token.split(" ")[1]).getBody().getSubject();
            return Integer.parseInt(id);
        }else {
            String id = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
            return Integer.parseInt(id);
        }

    }
}
